<?php



use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

// require __DIR__.'/../bootstrap/autoload.php';

use SmsUtils;

// define(APP_BASE, "/htdocs/tt201801/");
//require_once "/htdocs/tt201801/app/Http/Controllers/SignatureHelper.php";

//require_once "/htdocs/tt201801/app/Http/Controllers/sms/TopSdk.php";
//use TopClient;
//use AlibabaAliqinFcSmsNumSendRequest;
//
//use Aliyun\DySDKLite\SignatureHelper;

class UserMgmrController {

    public function pageLogin(){
		return view('user.login', ['name' => 'seven']);
    }

	function generate_code($length = 6) {
		return rand(pow(10,($length-1)), pow(10,$length)-1);
	}
	public function requestVerifyCode(Request $request){
		$username = $request->input('phone');

		$result_arr = array();

		if(empty($username)){
			$result_arr = array(
					'code'=>'2',
					'msg'=>'手机号不能为空'
			);
		}else{
			$code = $this->generate_code(6);
			///发短信：阿里云通信
//			ini_set("display_errors", "on"); // 显示错误提示，仅用于测试时排查问题
//			set_time_limit(0); // 防止脚本超时，仅用于测试使用，生产环境请按实际情况设置
//			header("Content-Type: text/plain; charset=utf-8"); // 输出为utf-8的文本格式，仅用于测试
			//$res = $this->sendSms($username, $code);

			///发短信：阿里大于
//			$accessKeyId = "24781099";
//			$accessKeySecret = "c6c8723ae999706d2075aba51f2ca765";
//			$c = new TopClient;
//			$c->appkey = $accessKeyId;
//			$c->secretKey = $accessKeySecret;
//			$req = new AlibabaAliqinFcSmsNumSendRequest;
//			$req->setSmsType("normal");
//			$req->setSmsFreeSignName("秘录小典");
//			$req->setSmsParam("{\"verify_code\":\"$code\"}");
//			$req->setRecNum($username);
//			$req->setSmsTemplateCode("SMS_123455003");
//			$res = $c->execute($req);  //res就是阿里大于返回的结果

            $res = SmsUtils::sendSms($username, $code);

			///插入数据
			DB::table('verify_code')->insert([
					'username'=>$username,
					'code'=>$code . "",
					'createTime'=>time() . "",
					'expireTime'=>(60 + time()) . ""
			]);

			$result_arr = array(
					'code'=>'0',
					'msg'=>$res,
                    'result'=>"{}"
//					'result'=>array(
//							'code'=>$code
//					)
			);
		}
		return response()->json($result_arr);
	}


	/**
	 * 发送短信
	 */
//	function sendSms($phone, $code) {
//
//		$params = array ();
//
//		// *** 需用户填写部分 ***
//
//		// fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
//		$accessKeyId = "LTAISdEYPEVQ9jAP";
//		$accessKeySecret = "3AJNBpSJGgiY8ipNVlNa6RrEu24Pdr";
//		// fixme 必填: 短信接收号码
//		$params["PhoneNumbers"] = $phone; //"15011571302";
//
//		// fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
//		$params["SignName"] = "秘录小典";
//
//		// fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
//		$params["TemplateCode"] = "SMS_123455003";
//
//		// fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
//		$params['TemplateParam'] = Array (
//				"verify_code" => $code //{"verify_code":"1234"}
//		);
//
//		// fixme 可选: 设置发送短信流水号
//		//$params['OutId'] = "12345";
//
//		// fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
//		//$params['SmsUpExtendCode'] = "1234567";
//
//
//		// *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
//		if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
//			$params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
//		}
//
//		// 初始化SignatureHelper实例用于设置参数，签名以及发送请求
//		$helper = new SignatureHelper();
//
//		// 此处可能会抛出异常，注意catch
//		$content = $helper->request(
//				$accessKeyId,
//				$accessKeySecret,
//				"dysmsapi.aliyuncs.com",
//				array_merge($params, array(
//						"RegionId" => "cn-hangzhou",
//						"Action" => "SendSms",
//						"Version" => "2017-05-25",
//				))
//		);
//
//		return $content;
//	}


	public function registV1(Request $request){
		$username = $request->input('username');
		$password = $request->input('password');
		$code = $request->input('code');

		$result_arr = array();

		if(empty($username) || empty($password) || empty($code)){
			$result_arr = array(
					'code'=>'2',
					'msg'=>'所有字段不能为空'
			);
		}else{
			$codeRows = DB::table('verify_code')->where("username", "=", $username)->orderBy('id','desc')->get();
			if(count($codeRows) == 0){
				$result_arr = array(
						'code'=>'1',
						'msg'=>'未知错误'
				);
			}else{
				$codeRow = $codeRows[0];
				if($code != $codeRow->code){
					$result_arr = array(
							'code'=>'3',
							'msg'=>'验证码错误'
					);
				}else{
					$users = DB::table('users')->where("username", "=", $username)->get();
					if(count($users) != 0){
						$result_arr = array(
								'code'=>'4',
								'msg'=>'用户已存在'
						);
					}else{
						$sid = $this->guid();
						DB::table('users')->insert([
								'username'=>$username,
								'password'=>$password,
								'sid' => $sid
						]);
						$result_arr = array(
								'code'=>'0',
								'msg'=>'ok',
								'result'=>array(
										'sid'=>$sid
								)
						);
					}
				}
			}


		}
		return response()->json($result_arr);
	}


    public function updateUserInfo(Request $request){

        //check login
        $sid = $request->header('sid');
        if(empty($sid)){
            $result_arr = array(
                'code'=>'1',
                'msg'=>'未登录，sid为空'
            );
            return response()->json($result_arr);
        }else{
            $users = DB::table('users')->where("sid", "=", $sid)->get();
            if(count($users) == 0){
                $result_arr = array(
                    'code'=>'2',
                    'msg'=>'用户不存在'
                );
                return response()->json($result_arr);
            }
        }


        $data = $request->input('data');
        $user_id = $request->input('user_id');

        $result_arr = array();

        if(empty($data) || empty($user_id)){
            $result_arr = array(
                'code'=>'2',
                'msg'=>'所有字段不能为空'
            );
        }else{
            $users = DB::table('users')->where("id", "=", $user_id)->get();
            if(count($users) == 0){
                $result_arr = array(
                    'code'=>'3',
                    'msg'=>'用户不存在'
                );
            }else{
                DB::update('update users set extra1 = ? where id = ?',[$data, $user_id]);
                $result_arr = array(
                    'code'=>'0',
                    'msg'=>'ok'
                );
            }


        }
        return response()->json($result_arr);
    }

	public function login(Request $request){
		$username = $request->input('username');
		$password = $request->input('password');

		$result_arr = array();

		if(empty($username) || empty($password)){
			$result_arr = array(
					'code'=>'2',
					'msg'=>'所有字段不能为空'
			);
		}else{
			$users = DB::table('users')->where("username", "=", $username)->get();
			if(count($users) == 0){
				$result_arr = array(
						'code'=>'1',
						'msg'=>'用户不存在'
				);
			}else{
				$user = $users[0];
				if($user->password != $password){
					$result_arr = array(
							'code'=>'3',
							'msg'=>'密码错误'
					);
				}else{
					$result_arr = array(
							'code'=>'0',
							'msg'=>'ok',
							'result'=>array(
									'info'=>$user->extra1,
                                    'id'=>$user->id,
									'sid'=>$user->sid
							)
					);
				}

			}
		}
		return response()->json($result_arr);
	}

    public function regist(Request $request){

    	$username = $request->input('username');
    	$password = $request->input('password');
		$company = $request->input('company');
		$realname = $request->input('realname');

		$result_arr = array();

		if(empty($username) || empty($password) || empty($company) || empty($realname)){
			$result_arr = array(
					'code'=>'2',
					'msg'=>'所有字段不能为空'
			);
		}else{
			$userCount = DB::table('users')->where("username", "=", $username)->count();
			if($userCount > 0){
				//用户名重复
				$result_arr = array(
						'code'=>'1',
						'msg'=>'用户名重复--'.$username
				);
			}else{
				$sid = $this->guid();
				DB::table('users')->insert([
						'username'=>$username,
						'password'=>$password,
						'company'=>$company,
						'realname'=>$realname,
						'sid' => $sid
				]);
				$result_arr = array(
						'code'=>'0',
						'msg'=>'ok',
						'result'=>array(
								'sid'=>$sid
						)
				);
			}
		}

    	//return response(json_encode($result_arr));
		return response()->json($result_arr);
		
    }

    public function logout(Request $request){
        $sid = $request->input('sid');

        $result_arr = array(
            'code'=>'0',
            'msg'=>'ok'
        );
        return response()->json($result_arr);
    }


	public function delete(Request $request){
		$sid = $request->input('sid');
		$taskId = $request->input('taskId');
		$bywho = $request->input('bywho');

		$result_arr = array();

		if(empty($sid)){
			$result_arr = array(
					'code'=>'1',
					'msg'=>'未登录，sid为空'
			);
			return response()->json($result_arr);
		}

		if(empty($taskId)){
			//新建
			$result_arr = array(
					'code'=>'1',
					'msg'=>'必须指定要删除的id'
			);
			return response()->json($result_arr);

		}else{
			//update--结束
			DB::table('users')->where('id','=', $taskId)->delete();
			$result_arr = array(
					'code'=>'0',
					'msg'=>'ok',
					'result'=>array()
			);
		}

		return response()->json($result_arr);
	}

	function guid(){
		if (function_exists('com_create_guid')){
			return com_create_guid();
		}else{
			mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
			$charid = strtoupper(md5(uniqid(rand(), true)));
			$hyphen = chr(45);// "-"
			$uuid = chr(123)// "{"
					.substr($charid, 0, 8).$hyphen
					.substr($charid, 8, 4).$hyphen
					.substr($charid,12, 4).$hyphen
					.substr($charid,16, 4).$hyphen
					.substr($charid,20,12)
					.chr(125);// "}"
			return $uuid;
		}
	}
}

?>